<template>
  <el-select-v2
    v-model="value"
    :options="
      options.map(item => {
        if (typeof item === 'object' && item !== null) {
          return {
            ...item,
            [labelKey]: te(item[labelKey]) ? t(item[labelKey]) : item[labelKey]
          };
        }
        return item;
      })
    "
    :empty-values="[null, undefined, '']"
    :props="{
      value: valueKey,
      label: labelKey
    }"
    clearable
    popper-class="custom-header"
    v-bind="$attrs"
    @change="handleChange"
  >
    <template v-if="columns.length" #header>
      <div class="flex">
        <div
          v-for="(item, index) in columns"
          :key="index"
          class="flex-1"
          :style="{ width: item.width }"
        >
          {{ item.name }}
        </div>
      </div>
    </template>
    <template v-if="columns.length" #default="{ item }">
      <div class="flex">
        <div
          v-for="(v, index) in columns"
          :key="index"
          class="flex-1"
          :style="{ width: v.width }"
        >
          {{ item[v.key] }}
        </div>
      </div>
    </template>
  </el-select-v2>
</template>

<script lang="ts" setup>
import { computed, ref, useAttrs, watch } from "vue";
import type { CheckboxValueType } from "element-plus";
import type { columnsType } from "../type";
import { isArray } from "@pureadmin/utils";
import { useI18n } from "vue-i18n";

const props = defineProps({
  modelValue: {
    type: [String, Number, Array<object>]
  },
  options: {
    type: Array,
    default: () => []
  },
  valueKey: {
    type: String,
    default: ""
  },
  labelKey: {
    type: String,
    default: ""
  },
  columns: {
    type: Array as PropType<columnsType>,
    default: () => []
  }
});
const emit = defineEmits(["update:modelValue", "selectRow"]);
const { t, te } = useI18n();

const value = ref(props.modelValue);
// computed({
//   get() {
//     return value.value;
//   },
//   set(val) {
//     value.value = val[props.valueKey];
//     emit("update:modelValue", val[props.valueKey]);
//   }
// });

const handleChange = (val: CheckboxValueType) => {
  emit("update:modelValue", val);
  handleSelectRow(val);
};

const handleSelectRow = (val: CheckboxValueType) => {
  if (val && isArray(props.options)) {
    const find = props.options?.find(item => item[props.valueKey] === val);
    emit("selectRow", find);
  }
};

watch(
  () => props.modelValue,
  val => {
    value.value = val;
  }
);
</script>

<style lang="scss">
.custom-header {
  .el-checkbox {
    display: flex;
    height: unset;
  }
}
</style>
